<template>
  <div>
    <div v-if="select === 2">
      <el-select v-model="membershipLevelSet" multiple placeholder="请选择等级" :style="{ 'width': width }" @change="changeSelest">
        <el-option
          v-for="item in level"
          :key="item.id"
          :label="item.name"
          :value="item.levelId"
        />
      </el-select>
    </div>
    <div v-else>
      <el-select :value="value" placeholder="请选择等级" :style="{ 'width': width }" clearable @change="change">
        <el-option v-for="(item, index) in level" :key="index" :label="item.name" :value="item.levelId" />
      </el-select>
    </div>

  </div>

</template>

<script>
/**
 * 业务组件 - 会员等级
 */
export default {
  name: 'Level',
  props: {
    /** 数据源 */
    value: {
      type: String,
      default: ''
    },
    levelList: {
      type: String,
      default: ''
    },
    /** 宽度 */
    width: {
      type: String,
      default: '120px'
    },
    select: {
      default: ''
    }
  },
  data() {
    return {
      api: this.$u.api.MemberData,
      // 等级列表
      level: [],
      membershipLevelSet: []
    }
  },

  watch: {
    // 监听数据
    levelList: {
      immediate: true,
      handler(val) {
        if (val !== null) {
          this.membershipLevelSet = val.split(',')
        } else {
          // 处理不符合预期的情况，如 null 或非字符串类型
          this.membershipLevelSet = []
        }
      }
    }
  },
  created() {
    // 初始化数据
    this.initData()
  },
  methods: {
    // 初始化数据
    initData() {
      this.api.level().then(res => {
        this.level = res.data
      })
    },
    changeSelest(e) {
      if (Array.isArray(e)) {
        e = e.join(',')
      } else if (e !== null && typeof e !== 'string') {
        e = e.toString()
      }
      if (e === '') {
        e = null
      }
      this.$emit('input', e)
      this.$emit('change', this.getLevel(e))
    },
    change(e) {
      this.$emit('input', e)
      this.$emit('change', this.getLevel(e))
    },
    // 初始化会员等级数据源
    getLevel(type) {
      return this.level.filter(item => parseInt(item.levelId) === parseInt(type))[0]
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep{
  .el-input{
    width: 100% !important;
  }
}
</style>
